$(function(){
	var $major_types = [];
	var $minor_types = [];
	var $minor_types_by_major = {};
	var $suppliers = null;
	var convert = function(product) {
		return [
			product.id,
			product.name,
			product.minorType,
			product.unit,
			product.price,
			product.type || null,
			product.supplier,
			null
		];
	};
	$('.refresh-link').click(function() {
		var task0 = $.get('../' + Feces.url.product_major_types + '.json').done(function(result){
			$major_types = result.data.sort(function(a, b){ return a.id - b.id; });
			$.each($major_types, function(){
				this.text = this.name;
			});
			$('#new-major').select2({ data: $major_types });
			$('#new-minor').select2();
		});
		var task1 = $.get('../' + Feces.url.product_minor_types + '.json').done(function(result){
			$minor_types = result.data.sort(function(a, b){ return a.id - b.id; });
			$.each($minor_types, function(){
				this.text = this.name;
				var major_id = this.majorType.id;
				var minor_types = $minor_types_by_major[major_id];
				if (minor_types) {
					minor_types.push(this);
				} else {
					$minor_types_by_major[major_id] = [this];
				}
			});
		});
		var task2 = $.get('../' + Feces.url.suppliers + '.json').done(function(result){
			$suppliers = result.data.sort(function(a, b){ return a.id - b.id; });
			$.each($suppliers, function(){
				this.text = this.name;
			});
			$('#new-supplier').select2({ data: $suppliers });
		});
		$.when(task0, task1, task2).done(function(){
			$('#display').dataTable({
				ajax: {
					url: '../' + Feces.url.products + '.json',
					dataSrc: function(response){
						return response.data.map(convert);
					}
				},
				stateSave: true,
				createdRow: function(row, data, dataIndex){
					$(row).data({ id: data[0] });
					$('td:eq(0)', row).data({ name: 'id' });
					$('td:eq(1)', row).data({
						name: 'name',
						type: 'text',
						title: '商品名',
						placeholder: '请输入商品名'
					}).attr('data-editable', true);
					$('td:eq(2)', row).data({
						name: 'minor_id',
						type: 'product_type',
						title: '商品分类',
						value: data[2].id,
						placeholder: '请选择商品分类',
						major_types: $major_types,
						minor_types: $minor_types,
						minor_types_by_major: $minor_types_by_major
					}).attr('data-editable', true).text(data[2].majorType.name + ' / ' + data[2].name);
					$('td:eq(3)', row).data({
						name: 'unit',
						type: 'text',
						title: '计量单位',
						placeholder: '请输入计量单位',
					}).attr('data-editable', true);
					$('td:eq(4)', row).data({
						name: 'price',
						type: 'number',
						title: '原价',
						min: 0,
						step: 0.01,
						placeholder: '请输入原价',
					}).attr('data-editable', true);
					$('td:eq(5)', row).data({
						name: 'type',
						type: 'text',
						title: '型号',
						placeholder: '请输入型号',
						validate: null
					}).attr('data-editable', true);
					$('td:eq(6)', row).data({
						name: 'supplier_id',
						type: 'select2',
						title: '供应商',
						value: data[6].id,
						source: $suppliers
					}).attr('data-editable', true).text(data[6].name);
					$('td:eq(7)', row).append(
						$('<a>')
							.addClass('btn btn-circle btn-info')
							.attr('href', 'product.html?id=' + data[0])
							.attr('title', '查看详细信息')
							.html('<em class="fa fa-info"></em>')
					).append(' ').append(
						$('<a>')
						.addClass('btn btn-circle btn-danger')
						.attr('href', 'javascript:void(0);')
						.attr('title', '删除商品')
						.html('<em class="fa fa-trash-o"></em>')
						.click(function(){
							var link = $(this);
							$.ajax({
								type: 'DELETE',
								url: '../' + Feces.url.product + '.json',
								data: { id: link.closest('tr').data('id') }
							}).done(function(result){
								if (result.status === 0) {
									toastr.success('删除成功');
									link.closest('table').dataTable().fnDeleteRow(dataIndex);
								} else {
									toastr.error('删除失败: ' + result.message);
								}
							}).fail(function(){
								toastr.error('删除失败');
							});
						})
					);
					$('[data-editable=true]', row).each(function(){
						var cell = $(this);
						cell.wrapInner($('<a>')).children().editable($.extend({
							pk: $(this).closest('tr').data('id'),
							emptytext: '无',
							ajaxOptions: { type: 'PUT' },
							url: '../' + Feces.url.product + '.json',
							success: function(response, new_value){
								if (response.status !== 0) {
									return response.message;
								}
							},
							validate: function(value){
								if($.trim(value) === '') {
									return '不能为空';
								}
							}
						}, cell.data()));
					});
				},
				destroy: true
			});
			$('#new-major').on('change', function(){
				$('#new-minor')
					.empty()
					.append('<option>')
					.select2({ data: $minor_types_by_major[$(this).val()] })
					.prop("disabled", false);
			});
		});
		$('#new').submit(function(){
			event.preventDefault();
			var form = this;
			$.post('../' + Feces.url.product + '.json', $(this).serialize()).done(function(result){
				if (result.status === 0) {
					$('#display').dataTable().fnAddData(convert(result.data));
					form.reset();
					toastr.success('创建成功');
				} else {
					toastr.error('创建失败');
				}
			}).fail(function(){
				toastr.error('创建失败');
			});
		});
		$('.input-group.date').datepicker({
			todayBtn: "linked",
			keyboardNavigation: false,
			forceParse: false,
			calendarWeeks: true,
			autoclose: true
		});
		$('.i-checks').iCheck({
			checkboxClass : 'icheckbox_square-green',
			radioClass : 'iradio_square-green'
		});
	}).click();
});